<template>
  <div class="table-ddl">
    <je-editor-code
      :value="sqlData"
      language="sql"
      height="100%"
      :readonly="true"
      :editor-options="{ minimap: { enabled: false } }"
    />
  </div>
</template>

<script>
  import { defineComponent, ref, onMounted, watch } from 'vue';
  import { loadTableSql, loadViewSql } from '../../api/index';
  import { Modal, EditorCode } from '@jecloud/ui';
  import { isNotEmpty } from '@jecloud/utils';

  export default defineComponent({
    name: 'TableDdl',
    components: {
      JeEditorCode: EditorCode,
    },
    props: {
      tabKey: {
        type: String,
        default: '',
      },
      viewSql: {
        type: String,
        default: '',
      },
      tableType: {
        type: String,
        default: '',
      },
    },
    emits: ['copySqlData'],
    setup(props, { emit }) {
      //sql转义
      const sqlTransition = (sql) => {
        let sqlData = '';
        if (isNotEmpty(sql)) {
          const replaceRegex1 = /(\n)/g;
          sqlData = sql.replace(replaceRegex1, '<br/>');
          const replaceRegex2 = /(\t| {2})/g;
          sqlData = sqlData.replace(
            replaceRegex2,
            '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
          );
        }
        return sqlData;
      };

      const pkValue = ref(props.tabKey);
      const typeData = ref(props.tableType);
      let sqlData = ref('');
      if (pkValue.value == '' || pkValue.value == undefined) {
        sqlData = ref(props.viewSql);
      }

      watch(
        () => props.viewSql,
        (newVal) => {
          sqlData.value = newVal;
        },
      );

      const loadDdl = () => {
        if (typeData.value == 'VIEW') {
          loadViewSql({
            JE_CORE_RESOURCETABLE_ID: pkValue.value,
          })
            .then((data) => {
              emit('copySqlData', data.sql);
              sqlData.value = data.sql;
            })
            .catch((e) => {
              Modal.alert(e.message, 'error');
            });
        } else {
          loadTableSql({
            JE_CORE_RESOURCETABLE_ID: pkValue.value,
            type: 'TABLE',
          })
            .then((data) => {
              emit('copySqlData', data.sql);
              sqlData.value = data.sql;
            })
            .catch((e) => {
              Modal.alert(e.message, 'error');
            });
        }
      };

      onMounted(() => {
        if (pkValue.value != '' && pkValue.value != undefined) {
          loadDdl();
        }
      });

      return { sqlData, typeData };
    },
  });
</script>

<style lang="less" scoped>
  .table-ddl {
    height: 100%;
    overflow: auto;
  }
</style>
